package com.mikao.config;

import com.mikao.service.AuthService;
import com.mikao.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 授权拦截器
 * <br>
 * 拦截URI中有auth的请求，判断是否携带token，并校验 token的有效性
 *
 * @author KennyDavid
 */
@Slf4j
public class AuthInterceptor extends HandlerInterceptorAdapter {

    private final static String AUTH_URI = "/auth";

    @Autowired
    private AuthService authService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestUri = request.getRequestURI();
        if (!requestUri.contains(AUTH_URI)) {
            return true;
        }

        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            response.setStatus(HttpStatus.FORBIDDEN.value());
            log.info("请求头中缺少token");
            return false;
        }

        log.info("token: {}", token);
        Long userId = JwtUtil.validateToken(token);
        if (ObjectUtils.isEmpty(userId) || userId == 0L) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            log.info("该token无对应用户");
            return false;
        }

        log.info("userId: {}", userId);
        Boolean validateToken = authService.validateToken(userId, token);
        if (!validateToken) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            log.info("token已过期");
            return false;
        }
        log.info("token校验通过");
        return true;
    }
}
